package com.chianghao.rock;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import com.chianghao.auth.cache.IAuthCache;
import com.chianghao.auth.cache.model.Role;
import com.chianghao.auth.cache.model.resource.PathResource;
import com.chianghao.core.utils.CollectionUtils;
import com.chianghao.rock.system.entity.Route;
import com.chianghao.rock.system.entity.User;
import com.chianghao.rock.system.service.route.RouteService;
import com.chianghao.rock.system.service.user.UserService;


@SpringBootApplication
@MapperScan(basePackages = {"com.chianghao.rock.system.dao"})
public class AdminApplication implements CommandLineRunner {
	
	@Autowired
	UserService userService;
	
	@Autowired
	IAuthCache authCache;
	
	@Autowired
	RouteService routeService;
	
    public static void main(String[] args) {
        SpringApplication.run(AdminApplication.class, args);
    }

	@Override
	public void run(String... args) throws Exception {
		
		
		authCache.addWhileList(CollectionUtils.arrayToList(
				new PathResource("POST", "login", UUID.randomUUID().toString())
				));
		// 定义超级管理员角色
		Role supperRole = new Role() {
			@Override
			public String getKey() {
				return Constant.supperAdmin;
			}
		};
		
		// 设置哪些用户是超级管理员
		List<User> supperUser  = userService.queryAppSupperAdmin(); 
		for(User user:supperUser) {
			authCache.addUserRole(new com.chianghao.auth.cache.model.User() {
				@Override
				public String getKey() {
					return user.getId().toString();
				}}, CollectionUtils.arrayToList(supperRole));

		}
		
		
		// 添加超级管理员的资源
		List<Route> allRoute = routeService.queryAllApi();
		List<PathResource> resources = new ArrayList<PathResource>();
		for(Route route:allRoute) {
			resources.add(new PathResource(route.getApiMethod(), route.getApiPath(), route.getId().toString()));
		}
		authCache.addRoleResouce(supperRole, resources);
		
		
	}
}
